package com.fun.utils.request;

import com.fun.frame.SourceCode;
import com.fun.httpclient.FanLibrary;
import com.fun.profile.Constant;
import com.fun.utils.WriteRead;
import net.sf.json.JSONObject;
import org.apache.http.client.methods.HttpRequestBase;


/**
 * 从文件中读取接口相关参数，用来发送请求，实现接口请求的配置化
 * <p>从当前路径下获取后缀为.log的文件，以文件名为准读取文件内容</p>
 */
public class RequestFlie extends SourceCode {
	String url;
	String cookie;
	String requestType;
	String name;
	JSONObject info = new JSONObject();
	JSONObject params = new JSONObject();

	/**
	 * @param name
	 */
	public RequestFlie(String name) {
		this.name = name;
		getInfo();
		this.url = this.info.getString("url");
		requestType = this.info.getString("requestType");
		getParams();
		cookie = this.info.getString("cookie");
	}

	/**
	 * 获取当前目录下的配置文件，以数字开头，后缀是.log的
	 *
	 * @param i
	 */
	public RequestFlie(int i) {
		this(i + Constant.EMPTY);
	}

	/**
	 * 从配置文件中读取信息，组成一个json对象
	 */
	private void getInfo() {
		String filePath = Constant.WORK_SPACE + name + Constant.FILE_TYPE_LOG;
		output("配置文件地址：" + filePath);
		this.info = WriteRead.readTxtByJson(filePath);
	}

	/**
	 * 获取请求参数
	 */
	private void getParams() {
		String params = info.getString("params");
		String[] args = params.split(";");
		int length = args.length;
		for (int i = 0; i < length; i++) {
			String[] keyValue = args[i].split("=");
			String key = keyValue[0];
			String value = keyValue[1];
			this.params.put(key, value);
		}
	}

	/**
	 * 根据info组成请求
	 *
	 * @return
	 */
	public HttpRequestBase getRequest() {
		HttpRequestBase requestBase = requestType.equalsIgnoreCase(Constant.REQUEST_TYPE_POST) ? FanLibrary.getHttpPost(this.url, this.params) : FanLibrary.getHttpGet(this.url, this.params);
		requestBase.addHeader(Constant.REQUEST_HEADER_COOKIE, cookie);
		return requestBase;
	}
}
